import { useEffect, useMemo, useState } from 'react'

export default function UseMemo() {
  const [count, setCount] = useState(0)
  const [curTime, setCurTime] = useState('')

  const useTime = () => {
    useEffect(() => {
      const intervalId = setInterval(() => {
        const time = new Date()
        setCurTime(time.toLocaleString())
      }, 1000)

      return () => {
        clearInterval(intervalId)
      }
    }, [])

    return curTime
  }

  const time = useTime()

  const arr = useMemo(() => {
    const temp = []
    for (let i = 0; i < count; i++) {
      if (i % 2 === 0) {
        temp.push(i)
      }
    }
    return temp
  }, [count])

  return (
    <div title='useMemo'>
      <form>
        <div>{time}</div>
        <label htmlFor='num'>Your number:</label>
        <input
          type='number'
          value={count}
          onChange={(event) => {
            // 设置最大值为 100000
            const num = Math.min(100_000, Number(event.target.value))
            setCount(num)
          }}
        />
      </form>
      <p>
        有{arr.length}偶数在 0 到 {count} 之间:<span>{arr.join(', ')}</span>
      </p>
      <span>2</span>
      {/*不会渲染*/}
      {}
      {}
      <span>3</span>
    </div>
  )
}
